#include <string.h>
#include <stdio.h>

#include "thread.h"
#include "ipc.h"

#include "serial.h"

static void *uart_func(void *arg)
{
    mt_ssize_t lenght;
    mt_device_t *uart;
    mt_uint8_t buffer[128];
    mt_serial_config_t config;
    
    uart = mt_device_open("UART5", MT_DEVICE_RDWR);
    if(uart == MT_NULL)
    {
        printf("open uart failed\r\n");
        return (void*)MT_EINVAL;
    }
    mt_device_ioctl(uart, SERIAL_GET_CONFIG, &config);
    config.baud_rate = BAUD_RATE_38400;
    mt_device_ioctl(uart, SERIAL_SET_CONFIG, &config);
    while(1)
    {
        memset(buffer, 0, sizeof(buffer));
        lenght = mt_device_read(uart, buffer, sizeof(buffer));
        if(lenght <= 0)
        {
            printf("read data from uart faied\r\n");
            continue;
        }
        if(mt_device_write(uart, buffer, lenght) != lenght)
            printf("write data to uart faied\r\n");
    }
}

int uart_test(void)
{
    mt_thread_t *handle;

    handle = mt_thread_create("uart_func", 
                              uart_func, 
                              MT_NULL, 
                              1024, 
                              2, 
                              5);
    if(handle == MT_NULL)
    {
        printf("create thrtead faied\r\n");
        return -1;
    }
    mt_thread_start(handle);
    
    return 0;
}
